﻿using RemoteDesktopLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RemoteDesktopClient
{
    public partial class upfileForm : Form
    {
        public ServerService.ServerClient serverClient { get; set; }
        private BackgroundWorker worker = new BackgroundWorker();
        public upfileForm()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            
	        if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            if(txtFilePath.Text.Equals(""))
            {
                MessageBox.Show("Bạn chưa chọn file để up", 
                                "Error", 
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                return;
            }

            string server_folder = @"C:\Uploaded\"; 
            //Đường dẫn đích
            string serverfilepath = server_folder + Path.GetFileName(txtFilePath.Text);
            //Đường dẫn nguồn
            string filepath = txtFilePath.Text;

            byte[] buffer = null;
            using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
            }

            if (buffer != null)
            {
                try
                {
                    try
                    {
                        serverClient.SetFolderUploaded(server_folder);
                        serverClient.UploadFile(serverfilepath, buffer);
                        MessageBox.Show("Upload Successful!");
                    }
                    catch(Exception ex)
                    {
                        Logger.Error(ex, "Error upfile");
                        MessageBox.Show("Upload Failed!");
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Some error unexpected when uploading file.");
                }
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
